<script setup>
import { ref, reactive, getCurrentInstance, onMounted, h, nextTick, onUnmounted } from "vue";
import { goRouter, isJSON } from "@/utils";
import { ArrowLeftBold } from '@element-plus/icons-vue'

import IconType from "./components/IconType";
import ModelThree from "./components/ModelThree";
import VideoDialog from "./components/VideoDialog";
import SearchAlarm from "./components/SearchAlarm";
import AlarmList from "./components/AlarmList";
import moment from "moment";
import { globalStore } from "@/store/global"
const globalVue = globalStore();

const instance = getCurrentInstance();
const _this = instance.appContext.config.globalProperties; //vue3获取当前this

// 下拉数据
const cameraSelect = ref([]);

const timer = ref(null)

onMounted(async () => {
  init();
  cameraSelect.value = await globalVue.getSelect('cameraSelect');
});

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
})

function init() {
  getAlgorithmData();   // 左侧统计数据
  getAlarmList();   // 右侧表格数据
  getCameraList();   // 摄像头点位
  window.addEventListener('resize', () => ref_3dBox.value.calibration());
  timer.value = setInterval(() => {
    getCameraList();   // 摄像头点位
  }, 5000);
}

// 获取算法统计数据
function getAlgorithmTotal(cameraId){
  return new Promise((resolve, reject) => {
    let paramsTime = {};
    cameraId && (paramsTime['cameraId'] = cameraId);
    alarmData.searchForm?.date && (paramsTime['startTime'] = moment(alarmData.searchForm?.date).format("YYYY-MM-DD") + ' 00:00:00');
    alarmData.searchForm?.date && (paramsTime['endTime'] = moment(alarmData.searchForm?.date).format("YYYY-MM-DD") + ' 23:59:59');
    instance.proxy.$http.get('home.getAlarmTypeNum', {params: paramsTime}).then(res=>{
      resolve(res.data);
    }).catch(err => reject(err));
  })
}

// -------------------------------- 3D & 摄像头数据 --------------------------------
const ref_3dBox = ref(null);   // 3D DOM
const cameraTotal = reactive({
  cameraIdOld: null,
  dialogShow: false,
  data: {algorithmList: []},
})
// 获取 摄像头点位
function getCameraList() {
  instance.proxy.$http.get('statistics.getCameraList',{ params: {page: 1, size: 9999} }).then(res=>{
    ref_3dBox.value.addCamera(res.data.content, cameraTotal.cameraIdOld);
  }).catch(err => console.error(err))
}
// 摄像头点击 
async function cameraClick(showClick, cameraInfo) {
  // 点击新的摄像头，旧的摄像头清空active
  ref_3dBox.value.changeCamera(cameraInfo?.cameraData.id, cameraTotal.cameraIdOld)
  if (showClick) {
    cameraTotal.data = cameraInfo.cameraData;
    cameraTotal.cameraIdOld = cameraInfo.cameraData.id;
    cameraTotal.dialogShow = true;
    alarmData.searchForm.cameraId = cameraInfo.cameraData.id;
    alarmData.searchForm.date = null;
    getAlarmList(true);
    openShow(true);
    getAlgorithmData();
    getCamera(cameraInfo.cameraData.id);
  }else{
    clearCamera();
    openShow(false);
  }
}
async function getCamera(cameraId){
  let algorithmTotal = await getAlgorithmTotal(cameraId);
  cameraTotal.data['algorithmList'] = algorithmTotal.map(i => {
    i['icon'] = require(`@/assets/image/ico_alarm_${i.type}.png`);
    return i;
  }).sort((a,b) => a.type - b.type);
}
// 关掉摄像头视频弹框，清空所有摄像头active
function clearCamera(){
  cameraTotal.dialogShow = false;
  cameraTotal.data = {algorithmList: []};
  cameraTotal.cameraIdOld = '';
  ref_3dBox.value.changeCamera('无', cameraTotal.cameraIdOld)
}

// -------------------------------- 左侧统计数据 --------------------------------
const iconTypeData = reactive({
  list: [
    {
      id: 1,
      label: 'People Track Identification',
      value: 0,
      activeImage: require('@/assets/image/ico_track.png'),
      notImage: require('@/assets/image/ico_track2.png'),
    }, {
      id: 2,
      label: 'People Face Expression Identification',
      value: 0,
      activeImage: require('@/assets/image/ico_face.png'),
      notImage: require('@/assets/image/ico_face2.png'),
    }, {
      id: 3,
      label: 'People Risk Scoring',
      value: 0,
      activeImage: require('@/assets/image/ico_risk.png'),
      notImage: require('@/assets/image/ico_risk2.png'),
    }, {
      id: 4,
      label: 'Falling Detection',
      value: 0,
      activeImage: require('@/assets/image/ico_falling.png'),
      notImage: require('@/assets/image/ico_falling2.png'),
    }, {
      id: 5,
      label: 'Remnant Detection',
      value: 0,
      activeImage: require('@/assets/image/ico_remnant.png'),
      notImage: require('@/assets/image/ico_remnant2.png'),
    }, 
  ]
});
const ref_icon_type = ref(null);
// 左侧统计数据
async function getAlgorithmData(){
  let algorithmTotal = await getAlgorithmTotal();
  algorithmTotal.forEach(i => {
    iconTypeData.list.map(j => {
      if (j.label == i.name) {
        j.value = i.num
      }
      return j;
    })
  });
}
// tabs Click && 右侧select algorithm 的change事件
function iconTypeClick(item, arr=[]) {
  alarmData.searchForm.cameraId = '';
  if (arr.length) {
    ref_icon_type.value.screenActive(item, arr)
  }
  getAlarmList(true);
  openShow(true);
}
// 左侧点击 联动 右侧select
function changeTypeArr(arr =[]) {
  alarmData.searchForm.algorithm = arr;
}

// -------------------------------- 右侧下拉表格数据 --------------------------------
const alarmData = reactive({
  list: [],
  noMore: true,
  loading: false,
  searchForm: {
    date: moment().format("YYYY-MM-DD"),
    algorithm: [1,2,3,4,5]
  },
  pagination: {
    page: 1,
    size: 5,
    total: 0
  },
});
// isResrefh 是否重置列表    false：默认分页请求  true：重置请求
function getAlarmList(isResrefh = false) {
  if(isResrefh) {
    alarmData.list = [];
    alarmData.noMore = false;
    alarmData.pagination.page = 1;
  }
  if(alarmData.noMore) return;
  let params = {
    ...alarmData.pagination,
    algorithm: alarmData.searchForm.algorithm + '' || '',
    cameraId: alarmData.searchForm.cameraId || '',
  }
  alarmData.searchForm?.date && (params['startTime'] = moment(alarmData.searchForm?.date).format("YYYY-MM-DD") + ' 00:00:00');
  alarmData.searchForm?.date && (params['endTime'] = moment(alarmData.searchForm?.date).format("YYYY-MM-DD") + ' 23:59:59');
  alarmData.loading = true;
  instance.proxy.$http.get('statistics.getAlarmList',{ params }).then(res=>{
    if (alarmData.noMore) return;
    let {content, totalElements} = res.data;
    let arr = content.map(i => {
      i['time'] = moment(i.time).format('yyyy-MM-DD HH:mm:ss');
      i['attribution'] = isJSON(i.attribution) ? JSON.parse(i.attribution) : false;
      return i;
    });
    alarmData.list = alarmData.list.concat(arr);
    alarmData.pagination.total = totalElements;
    alarmData.loading = false;
    alarmData.pagination.page++;
    alarmData.noMore = alarmData.list.length >= totalElements;
  }).catch(err => alarmData.loading = false);
}
// DOM 操作
const ref_table_box_show = ref(false);
const ref_table_box = ref(null);
const ref_arrow_icon = ref(null);
const ref_open_dom = ref(null);
// show  Boolean值  true：打开侧栏  false：关闭侧栏
let openShow = (show = 'one') => {
  if (show !== 'one') {
    ref_table_box_show.value = !show;
  }
  if (ref_table_box_show.value) {
    ref_table_box.value.style.right = '-42%';
    ref_open_dom.value.style.right = '0';
    ref_open_dom.value.style.padding = '25px 5px 20px';
    ref_arrow_icon.value.style.transform = 'rotate(360deg)';
    ref_table_box_show.value = false;
  }else{
    ref_table_box.value.style.right = '0';
    ref_open_dom.value.style.right = '41%';
    ref_open_dom.value.style.padding = '20px 5px 25px';
    ref_arrow_icon.value.style.transform = 'rotate(180deg)'
    ref_table_box_show.value = true;
  }
}
// 告警点击  item：点击这个摄像头数据
function itemClick(item){
  // console.log(item, "告警点击");
  ref_3dBox.value.changeCamera(item.cameraId, cameraTotal.cameraIdOld);
  cameraTotal.cameraIdOld = item.cameraId;
}
function timeChange(){
  getCamera(alarmData.searchForm.cameraId);
  getAlgorithmData();
}
// 切换摄像头时，缩小之前的摄像头，放大新的摄像头   并更新弹框数据
function cameraChange(cameraId){
  ref_3dBox.value.changeCamera(cameraId, cameraTotal.cameraIdOld);
  getCamera(cameraId);
  ref_3dBox.value.refreshThree();
  cameraTotal.cameraIdOld = cameraId;
}

</script>
<template> 
  <div class="index">
    <IconType 
      ref="ref_icon_type" 
      :list="iconTypeData.list" 
      :defaultActive="alarmData.searchForm.algorithm" 
      @changeTypeArr="changeTypeArr"
      @iconTypeClick="iconTypeClick">
    </IconType>
    <ModelThree class="box_camera" ref="ref_3dBox" @cameraClick="cameraClick"></ModelThree>
    <VideoDialog 
      :show="cameraTotal.dialogShow"
      :cameraData="cameraTotal.data"
    ></VideoDialog>
    <div class="roll_data_open" ref="ref_open_dom" @click.stop="openShow()">
      <div class="mw_icon_arrow" ref="ref_arrow_icon"><ArrowLeftBold style="width: 20px;color: #ffffff" /></div>
    </div>
    <div class="roll_data" ref="ref_table_box">
      <div v-if="ref_table_box_show" style="height: 100%">
        <SearchAlarm 
          :searchForm="alarmData.searchForm"
          :algorithmSelect="iconTypeData.list" 
          :cameraSelect="cameraSelect"
          @algorithmChange="iconTypeClick"
          @timeChange="timeChange"
          @cameraChange="cameraChange"
          @clearCamera="clearCamera"
          @search="getAlarmList">
        </SearchAlarm>
        <AlarmList
          :list="alarmData.list"
          :noMore="alarmData.noMore" 
          :loading="alarmData.loading" 
          @load="getAlarmList" 
          @itemClick="itemClick"
        ></AlarmList>
      </div>
    </div>
  </div>
</template>
<style scoped lang="less">
.index {
  transition: all 0.5s;
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  position: relative;
  .roll_data_open{
    transition: all 0.5s;
    position: absolute;
    top: 50%;
    z-index: 100;
    right: 0;
    transform: translateY(-50%);
    border: 1px solid #ffffff;
    padding: 25px 5px 20px;
    border-radius: 15px 0 0 15px;
    border-right: 0px;
    cursor: pointer;
    .mw_icon_arrow{
      transition: all 0.5s;
    }
  }
  .roll_data{
    transition: all 0.5s;
    position: absolute;
    z-index: 50;
    top: 0;
    right: -42%;
    width: 41%;
    height: 100%;
    // background-color: rgba(0, 0, 0, 0.3);
    background-color: rgba(17, 58, 114, 0.45);
    padding: 0 0 15px;
    display: flex;
    flex-direction: column;
  }
  
.alarm_scroll{
  overflow: auto;
  padding: 15px;
  .no_data {
    display: block;
    text-align: center;
    color: #ccc;
    margin: 10px 0;
  }
  .alarm_item:hover{
    box-shadow: 0px 0px 15px 1px rgb(18 134 234);
    border: 1px solid #54D6FD;
    box-sizing: border-box;
  }
  .alarm_item{
    background-color: rgba(27, 44, 80, 0.5);
    padding: 15px;
    margin-bottom: 10px;
    color: #D9DBDC;
    .type_item{
      display: flex;
      flex-direction: column;
      width: fit-content;
      font-size: 14px;
      color: #D9DBDC;
      margin-right: 30px;
      span:nth-child(1){
        color: #B2B6B7;
      }
      span:nth-child(2){
        line-height: 2;
      }
    }
    .alarm_item_line{
      width: 100%;
      height: 1px;
      background-color: #435B77;
      margin: 15px 0;
    }
    .alarm_item_valList{
      display: flex;
      flex-flow: row wrap;
      justify-content: space-between;
      .alarm_item_val{
        width: 49%;
      }
    }
    .alarm_item_img{
      width: 100%;
      // width: 173px;
      // height: 97px;
    }
    .alarm_item_title{
      font-size: 20px;
      color: #fff;
      margin-bottom: 15px;
    }
  }
}
}
</style>